package com.sso.oauth2.server.config.auath2.impl;

import org.apache.commons.lang3.StringUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.ClientRegistrationException;
import org.springframework.security.oauth2.provider.NoSuchClientException;
import org.springframework.security.oauth2.provider.client.BaseClientDetails;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * TODO 这里是类注释
 *
 * @author yins
 * @date 2021/07/22 16:41
 **/
//@Service
public class CustomClientDetailsImpl implements ClientDetailsService {

    private static final PasswordEncoder PASSWORD_ENCODER = new BCryptPasswordEncoder();

    private static final Map<String, String> CLIENT_MAP = new HashMap<>();

    private String grantTypes = "authorization_code,password,implicit,client_credentials";

    static {
        CLIENT_MAP.put("duia_client", PASSWORD_ENCODER.encode("duia2018"));
        CLIENT_MAP.put("duia_client1", PASSWORD_ENCODER.encode("duia2018"));
        CLIENT_MAP.put("duia_client2", PASSWORD_ENCODER.encode("duia2018"));
    }

    @Override
    public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {
        String pwd = CLIENT_MAP.get(clientId);
        if (StringUtils.isNotBlank(pwd)) {
            BaseClientDetails clientDetails = new BaseClientDetails(
                    clientId,
                    "",
                    "all",
                    grantTypes,
                    null,
                    "http://localhost:21000/login");
            clientDetails.setClientSecret(pwd);
            clientDetails.isAutoApprove("all");
            clientDetails.setAccessTokenValiditySeconds(120);
//            clientDetails.setRefreshTokenValiditySeconds();
            return clientDetails;
        } else {
            throw new NoSuchClientException("No client with requested id: " + clientId);
        }
    }
}
